<script setup lang="ts">
import ExpectedDeliveryTime from '@/subcontract/home/submitOrder/component/orderProduct/component/ExpectedDeliveryTime.vue';
import ServiceTime from '@/subcontract/home/submitOrder/component/orderProduct/component/ServiceTime.vue';

interface IProps {
  products: IProductInformation[];
  callerDevicePartInfo: IObtainCallerDevicePartInfoRes;
  calculateOrderPriceInfo: ICalculateOrderPriceRes;
  amount: {
    packagingFee: number; // 包装费
    deliveryFee: number; // 配送费
    payTotalFee: number; // 总价
    payableTotalFee: number; // 未抵扣养老金/物业金 总价
    depositFee: number; // 抵押金
    promoteGainFee: number; //推广优惠金额
  };
}

interface IState {
  isOpen: boolean;
  productGroup: ICalculateOrderPriceRes['list'];
  discountOld: boolean;
  discountPmc: boolean;
}

type EmitEvents = {
  (event: 'discountChange', payload: { discountOld: boolean; discountPmc: boolean }): void;
  (event: 'expectedTimeChange', payload: { date: string; orderId: number; key: string }): void;
  (event: 'serverTimeChange', payload: { date: string; orderId: number; key: string }): void;
};

const props = defineProps<IProps>();
const emits = defineEmits<EmitEvents>();
const state = reactive<IState>({
  isOpen: false,
  productGroup: [],
  discountOld: false,
  discountPmc: false,
});

onMounted(() => {
  state.productGroup = groupByBusinessId(props.calculateOrderPriceInfo.list);
  if (props.calculateOrderPriceInfo.discountOld) state.discountOld = true;
  if (props.calculateOrderPriceInfo.discountPmc) state.discountPmc = true;
});

// 根据businessId进行商户合并
function groupByBusinessId(data: ICalculateOrderPriceRes['list']) {
  const map = new Map();
  data.forEach((item) => {
    const existing = map.get(item.businessId);
    if (existing) {
      existing.list = existing.list.concat(item.list);
    } else {
      map.set(item.businessId, { ...item, list: item.list });
    }
  });
  return Array.from(map.values());
}

// 养老金物业金选择器选择事件
const handleCheckboxChange = (e: any, slot: number) => {
  if (slot === 1) state.discountOld = e.detail;
  if (slot === 2) state.discountPmc = e.detail;
  emits('discountChange', { discountOld: state.discountOld, discountPmc: state.discountPmc });
};
</script>

<template>
  <view class="bg-white c-br px-12px pt-1px pb-12px mt-12px">
    <template v-for="(group, groupIndex) in state.productGroup" :key="groupIndex">
      <van-divider contentPosition="left">
        <text class="c-color-black fw-bold">{{ group.businessName }}</text>
      </van-divider>
      <view class="mb-12px" v-for="(item, index) in group.list" :key="index">
        <van-transition :show="index > 1 ? !!state.isOpen : true" name="fade">
          <view class="flex">
            <view class="w-60px h-60px c-br overflow-hidden">
              <image class="w-full h-full" :src="item.images.split(',')[0]" lazy-load mode="aspectFill" />
            </view>
            <view class="pl-8px box-border overflow-hidden flex-1 flex flex-col justify-between">
              <view class="flex justify-between">
                <view class="flex-1 flex items-center">
                  <view v-if="item.activePrice" class="w-20px h-20px rounded-50% bg-red text-white mr-4px c-text-12 flex justify-center items-center">折</view>
                  {{ item.name }}
                </view>
                <text class="fw-bold c-text-16 ml-4px"><text class="c-text-10">¥</text> {{ item.activePrice || item.salePrice }}</text>
              </view>
              <view class="c-text-color-grey c-text-ellipsis-2 my-4px c-text-12" v-if="item.goodsType !== 2"> {{ item.strSpecVal && item.strSpecVal !== '无' ? item.strSpecVal : '' }}</view>
              <view class="c-text-color-grey c-text-ellipsis-2 my-4px c-text-12" v-else>
                <text v-for="(relations, relationsIndex) in item.oGRelations">
                  {{ relations.name }} {{ relations.sku && relations.sku !== '无' ? `${relations.sku}` : '' }}
                  {{ relationsIndex !== item.oGRelations.length - 1 ? '、' : '' }}
                </text>
              </view>
              <view class="w-full" v-if="item.activePrice">
                <view class="px-4px py-1px rounded-4px border-1px border-red border-solid text-red inline-flex items-center c-text-10"> <i class="i-fa:tags mr-2px" /> {{ ((item.activePrice / item.salePrice) * 10).toFixed(2) }}折，限{{ item.activeDiscount }}份 </view>
              </view>
              <view class="text-align-end">x {{ item.nums }}</view>
            </view>
          </view>
          <!--    服务时间      -->
          <ServiceTime v-if="item.goodsType === 4" :variantId="item.variantId" @change="(date) => emits('serverTimeChange', { date, orderId: item.goodsId, key: item.key })" />
          <!--    预计送达时间      -->
          <ExpectedDeliveryTime v-if="item.goodsType === 3 && item.expectedTime" :expectedTime="item.expectedTime" @change="(date) => emits('expectedTimeChange', { date, orderId: item.goodsId, key: item.key })" />
          <van-divider v-if="index !== group.list.length - 1" />
        </van-transition>
      </view>
    </template>
    <view v-if="props.calculateOrderPriceInfo.list.length > 1 ? props.products.length > 4 : props.products.length > 2" class="flex justify-center items-center" @click="state.isOpen = !state.isOpen"
      >{{ state.isOpen ? '收起' : '展开' }} <i :class="state.isOpen ? 'i-flowbite:angle-top-solid' : 'i-flowbite:angle-down-outline'" class="ml-8px"></i>
    </view>
  </view>
  <view class="bg-white c-br pt-1px pb-12px mt-12px overflow-hidden" v-if="props.amount.packagingFee || props.amount.deliveryFee || props.amount.depositFee || props.calculateOrderPriceInfo.discountOld || props.calculateOrderPriceInfo.discountPmc">
    <van-cell title="包装费" v-if="props.amount.packagingFee">
      <view class="text-align-right fw-bold c-text-16 c-color-black"> <text class="c-text-10">¥</text> {{ props.amount.packagingFee.toFixed(2) }} </view>
    </van-cell>
    <van-cell title="配送费" label="活动减配送费0.5元" v-if="props.amount.deliveryFee">
      <view class="text-align-right fw-bold c-text-16 c-color-black">
        <text class="c-text-10 c-text-color-grey line-through mr-4px">¥</text> <text class="c-text-color-grey line-through mr-8px"> {{ (props.amount.deliveryFee + 0.5).toFixed(2) }}</text> <text class="c-text-10">¥</text> {{ props.amount.deliveryFee.toFixed(2) }}
      </view>
    </van-cell>
    <van-cell title="押金" label="服务完成后自动扣除租赁费，退还剩余押金" v-if="props.amount.depositFee">
      <view class="text-align-right fw-bold c-text-16 c-color-black"> <text class="c-text-10">¥</text> {{ props.amount.depositFee.toFixed(2) }} </view>
    </van-cell>
    <van-cell title="养老金" v-if="props.calculateOrderPriceInfo.discountOld">
      <view class="flex justify-end">
        <van-checkbox :value="state.discountOld" label-position="left" @change="handleCheckboxChange($event, 1)">
          <view class="text-red">
            -<text class="c-text-10 mx-4px">¥</text> <text class="fw-bold c-text-16">{{ props.calculateOrderPriceInfo.discountOld.toFixed(2) }} </text>
          </view>
        </van-checkbox>
      </view>
    </van-cell>
    <van-cell title="物业金" v-if="props.calculateOrderPriceInfo.discountPmc">
      <view class="flex justify-end">
        <van-checkbox :value="state.discountPmc" label-position="left" @change="handleCheckboxChange($event, 2)">
          <view class="text-red">
            -<text class="c-text-10 mx-4px">¥</text> <text class="fw-bold c-text-16">{{ props.calculateOrderPriceInfo.discountPmc.toFixed(2) }} </text>
          </view>
        </van-checkbox>
      </view>
    </van-cell>
  </view>
</template>
